package com.aries.ui.widget.demo.module.title;

import com.aries.ui.util.StatusBarUtil;
import com.aries.ui.util.TextUtils;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.aries.ui.widget.demo.ResourceTable;
import com.aries.ui.widget.demo.adapter.TitleAdapter;
import com.aries.ui.widget.demo.base.BaseAbilitySlice;
import com.aries.ui.widget.demo.entity.TitleEntity;
import com.aries.ui.widget.demo.slice.TitleEditAbtivity;
import com.aries.ui.widget.demo.util.SizeUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.system.version.SystemVersion;

import java.util.ArrayList;
import java.util.List;

public class TitleAbility extends BaseAbilitySlice {

    protected Component vHeader;
    protected Ability mContext;
    protected boolean mIsFirstShow = true;
    protected int type = 0;
    protected boolean isWhite = true;
    protected Component mContentView;
    //    @BindView(R.id.drawer_root)
//    DrawerLayout drawerRoot;
//    @BindView(R.id.sv_slide)
    ScrollView svSlide;
    //    @BindView(R.id.titleBarDrawer)
//    TitleBarView titleBarDrawer;
//    @BindView(R.id.fLayout_drawer)
//    StackLayout fLayoutDrawer;
//    @BindView(R.id.rv_contentDrawer)
    ListContainer mRecyclerViewDrawer;
    //    @BindView(R.id.iv_headDrawer)
    Image ivHead;
    //    private TitleBarViewNew titleBar;
    private ListContainer mRecyclerView;
    private Switch sBtnImmersible;
    private Switch sBtnLight;
    private Switch sBtnLine;
    private DirectionalLayout lLayoutAlpha;
    private Slider sBarAlpha;
    private Text tvStatusAlpha;
    private boolean isImmersible = true;
    private boolean isLight = true;
    private boolean canImmersible = true;
    private boolean canLight = true;
    private TitleAdapter mAdapter;
    private int mAlpha = 102;
    private List<TitleEntity> mListTheme = new ArrayList<>();
    private Text textImmersible;
    private Text textLight;
    private Text textLine;

    @Override
    protected void initView(Intent intent) {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
//        super.onStart(intent);
//        setUIContent(getLayout());
        mContext = this.getAbility();
//        titleBar = (TitleBarViewNew) findComponentById(ResourceTable.Id_titleBar);

        initHeaders();
        initListContainer();
        initData();
//        setTitleBar();
    }

    public int getLayout() {
        return ResourceTable.Layout_ability_title;
    }

    public void setTitleBar() {
        titleBar.setTitleMainText("主标题")
                .setStatusBackgroundColor(RgbPalette.WHITE.asArgbInt())
                .setTitleSubText(getSubText())
                .setLeftTextDrawableWidth(SizeUtil.dp2px(24))
                .setLeftTextDrawableHeight(SizeUtil.dp2px(24))
                .setRightTextDrawable(ResourceTable.Media_ic_menu)
                .setRightTextDrawableWidth(SizeUtil.dp2px(24))
                .setRightTextDrawableHeight(SizeUtil.dp2px(24))
////                .setRightTextDrawableWidth(10)
////                .setRightText("菜单")
////                .setRightTextDrawableHeight(10)
                .setOnRightTextClickListener(component -> {
//                        drawerRoot.openDrawer(svSlide);
                    showToast("暂不支持DrawerLayout");
                });
    }

    private void showToast(String msg){
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setAlignment(TextAlignment.CENTER)
                .setAutoClosable(true)
                .setDuration(1000)
                .setText(msg)
                .show();
    }

    protected void initHeaders() {
        //背景高亮
//        drawerRoot.setScrimColor(Color.argb(10, 0, 0, 0));
        //海拔高度
//        drawerRoot.setDrawerElevation(40);
//        GlideManager.loadCircleImg("https://avatars3.githubusercontent.com/u/19605922?v=4&s=460", ivHead);
//        titleBarDrawer.setImmersible(getAbility(), isImmersible, isLight);
        vHeader = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_layout_title_header, null, false);
        textImmersible = (Text) vHeader.findComponentById(ResourceTable.Id_text_immersible);
        sBtnImmersible = (Switch) vHeader.findComponentById(ResourceTable.Id_sBtn_immersible);
        textLight = (Text) vHeader.findComponentById(ResourceTable.Id_text_light);
        sBtnLight = (Switch) vHeader.findComponentById(ResourceTable.Id_sBtn_light);
        textLine = (Text) vHeader.findComponentById(ResourceTable.Id_text_line);
        sBtnLine = (Switch) vHeader.findComponentById(ResourceTable.Id_sBtn_line);
        lLayoutAlpha = (DirectionalLayout) vHeader.findComponentById(ResourceTable.Id_lLayout_alpha);
        sBarAlpha = (Slider) vHeader.findComponentById(ResourceTable.Id_sBar_alpha);
        tvStatusAlpha = (Text) vHeader.findComponentById(ResourceTable.Id_tv_statusAlpha);
        initViewSettings();

//        setDrawerList();


    }

    private void initViewSettings() {
//        canImmersible = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        canImmersible = true;
        canLight = canImmersible;
        if (!canImmersible) {
            sBtnImmersible.setClickable(false);
            sBtnImmersible.setChecked(false);
            textImmersible.setText("不支持沉浸状态栏");
            sBtnLight.setClickable(false);
            sBtnLight.setChecked(false);
        }
        if (!canLight) {
            sBtnLight.setClickable(false);
            sBtnLight.setChecked(false);
            textLight.setText("不支持全透明");
            lLayoutAlpha.setVisibility(Component.HIDE);
        }
        sBtnImmersible.setCheckedStateChangedListener((absButton, isChecked) -> {
            isImmersible = isChecked;
            titleBar.setStatusAlpha(isImmersible ? 0 : 255);
//            titleBarDrawer.setStatusAlpha(isImmersible ? 0 : 255);
//            titleBarDrawer.setImmersible(mContext, isImmersible, isLight);
            textImmersible.setText(isChecked ? "沉浸" : "不沉浸");
            if (!isImmersible) {
                sBtnLight.setChecked(false);
                sBarAlpha.setProgressValue(255);
                StatusBarUtil.setStatusBarDarkMode(mContext);
            } else {
                if (isWhite) {
                    StatusBarUtil.setStatusBarLightMode(mContext);
                } else {
                    StatusBarUtil.setStatusBarDarkMode(mContext);
                }
            }
        });
        sBtnLight.setCheckedStateChangedListener((absButton, isChecked) -> {
            isLight = isChecked;
            int alpha = isLight ? 0 : 102;
            sBtnImmersible.setChecked(isLight);
            sBarAlpha.setProgressValue(alpha);
            titleBar.setStatusAlpha(alpha);
//                titleBarDrawer.setStatusAlpha(alpha);
            if (!isImmersible) {
                StatusBarUtil.setStatusBarDarkMode(mContext);
            } else {
                if (isWhite) {
                    StatusBarUtil.setStatusBarLightMode(mContext);
                } else {
                    StatusBarUtil.setStatusBarDarkMode(mContext);
                }
            }
            textLight.setText(isChecked ? "状态栏全透明" : "状态栏半透明");
        });
        sBtnLine.setCheckedStateChangedListener((absButton, isChecked) -> {
            titleBar.setDividerVisible(isChecked);
            textLine.setText(isChecked ? "显示下划线" : "隐藏下划线");
        });
        sBarAlpha.setValueChangedListener(new Slider.ValueChangedListener() {
            @Override
            public void onProgressUpdated(Slider slider, int progress, boolean b) {
                tvStatusAlpha.setText(progress + "");
                mAlpha = progress;
                if (canImmersible) {
                    sBtnImmersible.setChecked(mAlpha < 230);
                }
                if (canLight) {
                    sBtnLight.setChecked(mAlpha == 0);
                }
                titleBar.setStatusAlpha(mAlpha);
                if (mAlpha > 225 && isWhite) {
                    StatusBarUtil.setStatusBarDarkMode(mContext);
                } else {
                    if (isWhite) {
                        StatusBarUtil.setStatusBarLightMode(mContext);
                    }
                }
            }

            @Override
            public void onTouchStart(Slider slider) {

            }

            @Override
            public void onTouchEnd(Slider slider) {

            }
        });
//        drawerRoot.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
//            @Override
//            public void onDrawerOpened(View drawerView) {
//                super.onDrawerOpened(drawerView);
//                titleBar.setHeight(SizeUtil.dp2px(60));
//            }
//
//            @Override
//            public void onDrawerClosed(View drawerView) {
//                super.onDrawerClosed(drawerView);
//                titleBar.setHeight(SizeUtil.dp2px(48));
//            }
//        });
        setDefaultConfig();
    }

    private void setDefaultConfig() {
        sBarAlpha.setMaxValue(255);
        //默认打开就是沉浸式状态栏
        sBtnImmersible.setChecked(true);
        titleBar.setStatusAlpha(0);
        sBtnLight.setChecked(true);
        sBarAlpha.setProgressValue(0);
        sBtnLine.setChecked(true);
    }

    private void initListContainer() {
        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_rv_content);
        mRecyclerView.setScrollbarOverlapEnabled(false);
        mRecyclerView.setLayoutManager(new DirectionalLayoutManager());
//        if (!setItemClickable()) {
//            return;
//        }
        mRecyclerView.setItemClickedListener((listContainer, view, position, l) -> {
            TitleEntity entity = (TitleEntity) mAdapter.getItem(position);
            if(entity == null) return;
            if (entity.colorRes != 0) {
                isWhite = entity.colorRes == RgbPalette.WHITE.asArgbInt();

                titleBar.setBgColor(entity.colorRes)
                        .setLeftTextDrawableTintResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                        .setRightTextDrawableTintResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                        .setTitleMainTextColorResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                        .setTitleSubTextColorResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite);
                if (type > 0 && isImmersible) {
                    if (isWhite) {
                        StatusBarUtil.setStatusBarLightMode(mContext);
                    } else {
                        StatusBarUtil.setStatusBarDarkMode(mContext);
                    }
                }
            } else if(!TextUtils.isEmpty(entity.toast)){
                showToast(entity.toast);
            } else if (entity.activity != null) {
                try {
                    AbilitySlice instance = entity.activity.newInstance();
                    present(instance, new Intent());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (entity.dialog) {
                CharSequence[] listItem = new CharSequence[mListTheme.size()];
                for (int i = 0; i < mListTheme.size(); i++) {
                    listItem[i] = mListTheme.get(i).title;
                }

                String[] strs = new String[mListTheme.size()];
                for (int i = 0; i < mListTheme.size(); i++) {
                    strs[i] = mListTheme.get(i).title;
                }
                UIActionSheetDialog.ListSheetBuilder builder = new UIActionSheetDialog.ListSheetBuilder(this)
                        .addItems(strs)
                        .setTitle("切换TitleBarView颜色主题")
                        .setTitleTextColor(ComponentState.COMPONENT_STATE_EMPTY, RgbPalette.BLACK.asArgbInt())
                        .setItemsMinHeight(150)
                        .setPadding(100)
                        .setMarginTop(0)
                        .setGravity(LayoutAlignment.CENTER)
                        .setOnItemClickListener((dialog, itemView, position1) -> onItemClick(mListTheme.get(position1)));
                UIActionSheetDialog sheetDialog = builder.create();
                builder.hideDividersOfListAdapter(); //隐藏分割线
                builder.hideTitleDividersOfListAdapter(); //隐藏标题下方的分割线
                sheetDialog.show();
            }
        });
    }

    private ListContainer createThemeDialogContent() {
        ListContainer listview = new ListContainer(getContext());
        listview.setItemProvider(new BaseItemProvider() {
            @Override
            public int getCount() {
                return mListTheme.size();
            }

            @Override
            public Object getItem(int i) {
                return mListTheme.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
                Text text = new Text(getContext());
                text.setTextSize(50);
                text.setPadding(0, 10, 0, 10);
                text.setTextAlignment(TextAlignment.CENTER);
                text.setText(mListTheme.get(i).content);
                return text;
            }
        });
        return listview;
    }

    private void onItemClick(TitleEntity item) {
        isWhite = item.colorRes == RgbPalette.WHITE.asArgbInt();
        titleBar.setBgColor(item.colorRes)
                .setLeftTextDrawableTintResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                .setRightTextDrawableTintResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                .setTitleMainTextColorResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite)
                .setTitleSubTextColorResource(isWhite ? ResourceTable.Color_colorTextBlack : ResourceTable.Color_colorWhite);
        if (type > 0 && isImmersible) {
            if (isWhite) {
                StatusBarUtil.setStatusBarLightMode(mContext);
            } else {
                StatusBarUtil.setStatusBarDarkMode(mContext);
            }
        }
    }

    private void initData() {
        List<TitleEntity> list = new ArrayList<>();
        list.add(new TitleEntity("TitleBarView 自定义左中右View", "点击查看示例", TitleActionAbility.class));
        list.add(new TitleEntity("TitleBarView与底部EditText结合", "点击查看示例", TitleEditAbtivity.class));
        list.add(new TitleEntity("TitleBarView结合ConstraintLayout", "点击查看示例", "暂不支持ConstraintLayout"));
        list.add(new TitleEntity("TitleBarView结合CollapsingTitleBarLayout", "点击查看示例", "暂不支持CollapsingTitleBarLayout"));
        list.add(new TitleEntity("Toolbar结合CollapsingToolbarLayout", "点击查看示例", "暂不支持CollapsingToolbarLayout"));
        list.add(new TitleEntity("切换TitleBarView颜色主题", "点击切换主题", true));
        mAdapter = new TitleAdapter(list);
        mAdapter.addHeaderView(vHeader, 0, DirectionalLayout.VERTICAL);
        mRecyclerView.setItemProvider(mAdapter);

//        float value = getResourceManager().getElement(ResourceTable.String_dp_drawer_header).getFloat();
//        ViewUtil.getInstance().setViewHeight(fLayoutDrawer, (int) (value + StatusBarUtil.getStatusBarHeight(getContext())));
        mListTheme.clear();
        mListTheme.add(new TitleEntity("白色主题", "点击切换白色主题", 0xffffffff));
        mListTheme.add(new TitleEntity("红色主题", "点击切换红色主题", 0xffff4444));
        mListTheme.add(new TitleEntity("橙色主题", "点击切换橙色主题", 0xffffbb33));
        mListTheme.add(new TitleEntity("绿色主题", "点击切换绿色主题", 0xff99cc00));
        mListTheme.add(new TitleEntity("蓝色主题", "点击切换蓝色主题", 0xff33b5e5));
        mListTheme.add(new TitleEntity("紫色主题", "点击切换紫色主题", 0xffaa66cc));
        mListTheme.add(new TitleEntity("黑色主题", "点击切换黑色主题", 0xff000000));
    }


    private String getSubText() {
        return "系统" + SystemVersion.getVersion();
    }



    public ScrollView getSvSlide() {
        return svSlide;
    }

    public ListContainer getmRecyclerViewDrawer() {
        return mRecyclerViewDrawer;
    }

    public Image getIvHead() {
        return ivHead;
    }
}
